#include "text_query.h"
#include <fstream>
#include <sstream>

TextQuery::TextQuery(ifstream &is) : file(new vector<string>)
{
    string text;
    string word;
    while (getline(is, text)) {
        file->push_back(text);
        auto lineNum = file->size() - 1;
        istringstream line(text);
        while (line >> word) {
            auto &lines = wordMap[word];
            if (!lines) {
                lines.reset(new set<line_no>);
            }
            lines->insert(lineNum);
        }
    }
}

QueryResult TextQuery::query(const string &word)
{
    static shared_ptr<set<line_no>> noword(new set<line_no>);
    auto lines = wordMap.find(word);
    if (lines == wordMap.end()) {
        return QueryResult(word, file, noword);
    } else {
        return QueryResult(word, file, lines->second);
    }
}

ostream &print(ostream &out, const QueryResult &res)
{
    cout << res.word << " occurs " << res.lines->size() << " times" << endl;
    for (auto line : *res.lines) {
        cout << "\t(line " << line << ") " << (*res.file)[line] << endl;
    }
}
